<template>
  <div class="main">
    <div class="ent">录入特惠</div>
    <el-divider></el-divider>
    <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="110px">
      <div class="main_list part-form">
        <!-- 分类： -->
        <div class="part-form-div">
          <el-form-item label="分类：" required>
            <div class="part-form-item">
              <div class="classify-show">
                <category-group :selected-categorys="selectedShopCategorys"
                  :show-category-select-btn="showShopCategorySelectBtn" :single="true"
                  @selectOrReviseCategory="selectOrReviseCategory('shop')" />
                <div v-if="!dataForm.categoryId" class="warning">请先选择分类再填写以下商品信息！</div>
              </div>
              <category-selector v-if="categorySelectorVisible" ref="categorySelector"
                @getCategorySelected="getCategorySelected" />
            </div>
          </el-form-item>
        </div>
        <!-- 品牌： -->
        <div class="part-form-div">
          <el-form-item label="品牌：" required>
            <div class="brand">
              <img v-if="brandImgUrl" :src="brandImgUrl" class="brand-img">
              <el-tag v-if="brandName" class="br" :disable-transitions="true" closable @close="handleCloseBrand()">
                <span class="brandname">{{ brandName }}</span>
              </el-tag>
              <el-button type="text" :class="['sel-brand', dataForm.categoryId ? '' : 'gray']"
                @click="brandSelectHandle()">{{ brandName ? '修改' : '选择' }}品牌</el-button>
            </div>
            <brand-selector v-if="brandSelectVisible" ref="brandSelect" :is-single="true"
              @refreshSelectBrand="selectBrand" />
          </el-form-item>
        </div>
      </div>
      <div class="main_list part-form">
        <div class="part-form-div">
          <el-form-item label="酒种：" required>
            <el-select v-model="dataForm.spuId" size="mini" placeholder="选择酒种" @click.native="brand_lists()">
              <el-option v-for="item in brand_list" :key="item.seq" :label="item.name" :value="item.spuId" />
            </el-select>
          </el-form-item>
        </div>
        <div class="part-form-div">
          <el-form-item label="规格名称：" required>
            <el-select size="mini" v-model="dataForm.skuId" placeholder="选择规格" @click.native="spu_lists()">
              <el-option v-for="item in spu_list" :key="item.index" :label="item.skuName" :value="item.skuId" />
            </el-select>
          </el-form-item>
        </div>
      </div>
      <div class="main_list part-form">
        <div class="part-form-div">
          <el-form-item label="库存量：" prop="spuStock">
            <el-input type="number" v-model.trim="dataForm.spuStock" size="mini" placeholder="请输入总售卖数量" />
          </el-form-item>
        </div>
        <div class="part-form-div">
          <el-form-item label="特惠价：" prop="price">
            <el-input type="number" v-model.trim="dataForm.price" size="mini" placeholder="请输入特惠价" />
          </el-form-item>
        </div>
      </div>
      <div class="main_list part-form">
        <!-- <div class="part-form-div">
          <el-form-item label="原特惠价：">
            <el-input v-model="brandName" size="mini" placeholder="请输入原特惠价" />
          </el-form-item>
        </div> -->
        <div class="part-form-div">
          <el-form-item label="限购数量：" prop="quota">
            <el-input type="number" v-model.trim="dataForm.quota" size="mini" placeholder="请输入每人限购数量" />
          </el-form-item>
        </div>
      </div>
      <div class="main_list part-form">
        <div class="part-form-div">
          <el-form-item label="活动期限:" required>
            <el-date-picker v-model="createT" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
              start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </div>
      </div>
      <div class="bottom">
        <el-button class="subt" type="primary" @click="submit('dataForm')">立即发布</el-button>
        <el-button @click="back()">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  import categorySelector from '@/components/CategorySelector'
  import categoryGroup from '@/components/CategoryGroup'
  import * as api from '@/api/product/hot-sale'
  import * as api_s from '@/api/product/spu'
  import brandSelector from '@/components/BrandSelector'

  export default {
    components: {
      categorySelector,
      categoryGroup,
      brandSelector
    },
    data() {
      return {
        resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
        dataForm: {
          startTime: '',
          endTime: '',
          spuStock: null,
          price: '',
          quota: null,
          spuId: '', // 商品id
          brandId: '',
          brandName: '', // 品牌名称
          categoryId: '', // 分类id
          skuId: '', //规格id
          status: '0',
          categoryName: ''
        },
        createT: [],
        brand_list: [],
        spu_list: [],
        selectedShopCategorys: [], // 选中的店铺分类
        showShopCategorySelectBtn: true, // 店铺'选择分类'按钮显隐
        categorySelectorVisible: false, // 分类选择器弹窗显隐
        brandSelectVisible: false, // 品牌选择组件显隐
        brandName: '', // 品牌名称
        brandImgUrl: '', // 品牌logo
        rules: {
          spuStock: [{
            required: true,
            message: '请输入总售卖数量',
            trigger: 'blur'
          }],
          price: [{
            required: true,
            message: '请输入特惠价',
            trigger: 'blur'
          }],
          // quota: [{
          //   required: true,
          //   message: '请输入每人限购数量',
          //   trigger: 'blur'
          // }],
        }
      }
    },
    created() {

    },
    mounted() {},
    methods: {
      back(){
        this.$router.push('/product/hot-sale')
      },
      submit(formName) {
        if (!this.dataForm.categoryId) {
          this.$message({
            message: '请选择分类！',
            duration: 1000
          })
          return false
        }
        if (!this.dataForm.brandId) {
          this.$message({
            message: '请选择品牌！',
            duration: 1000
          })
          return false
        }
        if (!this.dataForm.spuId) {
          this.$message({
            message: '请选择酒种！',
            duration: 1000
          })
          return false
        }
        if (!this.dataForm.skuId) {
          this.$message({
            message: '请选择规格！',
            duration: 1000
          })
          return false
        }
        if (!this.createT) {
          this.$message({
            message: '请选择起止时间！',
            duration: 1000
          })
          return false
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.dataForm.price = this.dataForm.price * 100
            this.dataForm.brandName = this.brandName
            this.dataForm.startTime = this.createT[0]
            this.dataForm.endTime = this.createT[1]
            api.save(this.dataForm).then(data => {
              this.$message({
                message: '录入成功',
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.$router.push('/product/hot-sale')
                }
              })
            })
          } else {
            this.$message({
              message: '信息不完整！',
              duration: 1000
            })
            return false;
          }
        });
      },
      spu_lists() {
        console.log(this.dataForm.spuId)
        api_s.spu_list(this.dataForm.spuId).then(data => {
          this.spu_list = data
        })
      },
      // 获取--商品-根据品牌获取商品信息
      brand_lists() {
        api_s.brand_list(this.dataForm.brandId).then(data => {
          this.brand_list = data
        })
      },
      init() {
        const spuId = this.dataForm.spuId
        this.dataForm.spuId = spuId || ''
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (!this.dataForm.spuId) {
            return
          }
          api.getProdInfoPage(spuId).then(data => {
            console.log('获取data:', data)
            this.dataForm = data
            this.originalSpuAttrValueList = data.spuAttrValues
            this.backTotalStock = data.skus.reduce((res, {
              stock
            }) => {
              res += (stock || 0)
              return res
            }, 0)
            // 回显分类
            console.log('回显分类')
            this.getCategoryBack(data.categoryId, data.shopCategoryId)
            console.log(data.categoryId)
            console.log('回显分类')
            // 商品分类选择按钮
            this.showCategorySelectBtn = false
            if (data.brand?.imgUrl) {
              const img = data.brand.imgUrl
              if (img.indexOf('http://') === 0 || img.indexOf('https://') === 0) {
                this.brandImgUrl = img
              } else {
                this.brandImgUrl = this.resourcesUrl + img
              }
            }
            this.brandName = data.brand?.name // 品牌名字
            // 根据分类获取基本属性列表
            this.getAttrsByCategoryId(data.categoryId, data.spuAttrValues)
            // sku回显
            this.skuBackShow(data.shopCategoryId, data.skus) // 销售属性
          })
        })
      },
      /**
       * 添加指定品牌
       */
      selectBrand(brands) {
        if (brands) {
          this.brandImgUrl = brands[0].brandImgUrl
          this.dataForm.brandId = brands[0].brandId
          this.brandName = brands[0].brandName
          // 删除多余参数
          this.dataForm.brand = undefined
        }
      },
      /**
       * 选择/修改品牌
       */
      brandSelectHandle(value) {
        if (!this.dataForm.categoryId) {
          return
        }
        const brands = []
        brands.push({
          brandId: this.dataForm.brandId
        })

        this.brandSelectVisible = true
        this.$nextTick(() => {
          this.$refs.brandSelect.init(brands, this.dataForm.categoryId)
        })
      },
      /**
       * 删除品牌
       */
      handleCloseBrand() {
        this.brandImgUrl = ''
        this.brandName = ''
        this.dataForm.brandId = ''
        this.dataForm.brand = undefined
      },
      /**
       * 选择/修改分类
       */
      selectOrReviseCategory(key) {
        console.log('选择分类key:', key)
        this.selectKey = key
        this.categorySelectorVisible = true
        this.$nextTick(() => {
          this.$refs.categorySelector.init(0, key) // 1代表从创建分类进入
        })
      },
      /**
       * 获取子组件返回分类数据
       */
      getCategorySelected(selectedCategorys, parentId) {
        console.log('平台分类子组件数据：selectedCategorys:', selectedCategorys, '；parentId:', parentId)
        console.log(parentId)
        this.dataForm.categoryName = selectedCategorys[2]
        this.dataForm.categoryId = parentId
        console.log(this.dataForm.categoryId)
        this.categorySelectorVisible = false
        if (this.selectKey === 'platform') {
          this.selectedCategorys = selectedCategorys
          this.dataForm.categoryId = parentId
          this.getAttrsByCategoryId(parentId) // 请求基本属性
        } else {
          this.selectedShopCategorys = selectedCategorys
          this.dataForm.shopCategoryId = parentId
          this.querySalesAttrData() // 请求销售属性
        }
        console.log('店铺分类selectedShopCategorys:', this.selectedShopCategorys)
        console.log('平台分类selectedCategorys:', this.selectedCategorys)
        console.log('dataForm:', this.dataForm)
        console.log(this.dataForm.categoryId)

        console.log('tttttttttttttt')
      }
    }
  }
</script>

<style lang="scss" scoped>
  /* 取消input的上下箭头 */
  ::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }

  ::v-deep input::-webkit-outer-spin-button {
    -webkit-appearance: none !important;
  }

  ::v-deep input[type="number"] {
    -moz-appearance: textfield;
  }

  .main {
    margin: 0px 100px 20px 30px;

    .ent {
      font-weight: 600;
      font-size: 20px;
      height: 50pxpx;
      line-height: 50px;
      margin-bottom: 20px;
    }

    .part-form {
      display: flex;
      justify-content: space-between;
    }

    ::v-deep .el-form-item__label {
      font-size: 15px;
      line-height: 46px;
    }

    .part-form-item {
      font-size: 16px;
      width: 100%;

      // 分类
      .classify-show {
        line-height: 36px;

        .category-group {
          height: 3em;
          line-height: 3em;
        }

        .classify {
          display: inline-block;
          // min-width: 200px;
          line-height: 36px;
          padding: 0;
          border: 0;
          margin-right: 20px;
        }

        .change-classify {
          color: #02a1e9;
          cursor: pointer;
          margin-left: 0;
        }

        ::v-deep .change-category {
          font-size: 17px;
        }

        ::v-deep .category-sel1 {
          font-size: 16px;
          font-weight: bold;
          background-color: #f3f3f3;
          height: 45px;
          line-height: 40px;

          span {
            padding: 0 3px;
          }
        }

        .warning {
          display: inline-block;
          color: #e43130;
        }
      }

      // 轮播图
      .banner-tips {
        margin-top: 10px;
        font-size: 13px;
        color: #999;
      }
    }

    // 品牌
    .brand {
      display: flex;
      align-items: center;

      .brand-img {
        display: inline-block;
        margin-right: 6px;
        width: auto;
        max-width: 60px;
        height: auto;
        max-height: 40px;
      }

      .br {
        margin-right: 20px;
      }

      ::v-deep .el-button--text {
        color: #02a1e9;
        font-size: 17px;
        line-height: 17px;
      }

      .gray {
        color: #bcbcbc;
      }

      ::v-deep .sel-brand.gray:hover {
        cursor: not-allowed;
        font-size: 17px;
        line-height: 17px;
      }
    }

    .bottom {
      margin-top: 50px;
      margin-left: 30px;
      button{
        width: 120px;
      }
      .subt{
        margin-right: 30px;
      }
    }
  }
</style>
